using System;
using System.Collections.Generic;

namespace Bespoke.Common
{
	/// <summary>
	/// 
	/// </summary>
	public class CommandLineParser
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string this[string key]
		{
			get
			{
				return mArguments[key.ToUpper()];
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public int Count
		{
			get
			{
				return mArguments.Count;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public string[] Keys
		{
			get
			{
				string[] keys = new string[mArguments.Keys.Count];
				mArguments.Keys.CopyTo(keys, 0);
				return keys;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public string[] Values
		{
			get
			{
				string[] values = new string[mArguments.Values.Count];
				mArguments.Values.CopyTo(values, 0);
				return values;
			}
		}

		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="args"></param>
		public CommandLineParser(string[] args)
		{
			string name = String.Empty;
			string value = String.Empty;

			mArguments = new SortedDictionary<string, string>();

			int delimiterIndex = 0;
			foreach (string arg in args)
			{
				// Find a value delimiter in the current name=value pair
				delimiterIndex = arg.IndexOf(VALUE_DELIMITER);
				if (delimiterIndex == -1)
				{
					name = arg;
					value = String.Empty;
				}
				else
				{
					// Parse out the name and value from the pair
					name = arg.Substring(0, delimiterIndex).Trim().ToUpper();
					value = arg.Substring(delimiterIndex + 1).Trim().ToUpper();
				}
				
				mArguments.Add(name, value);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public bool ContainsKey(string key)
		{
			return mArguments.ContainsKey(key.ToUpper());
		}

		private static readonly string VALUE_DELIMITER = "=";

		private static SortedDictionary<string, string> mArguments;
	}
}
